import React, { useState } from 'react';
import { Layout, Avatar, Dropdown, Button, message, Menu } from 'antd';
import { MenuFoldOutlined, MenuUnfoldOutlined, UserOutlined, LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import { Link, useLocation } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { logoutUser } from '../redux/features/userSlice';
import Sidebar from './Sidebar';
import './Layout.css';

const { Header, Sider, Content } = Layout;

const AppLayout = ({ children }) => {
  const [collapsed, setCollapsed] = useState(false);
  const dispatch = useDispatch();
  const { userInfo, isAuthenticated } = useSelector((state) => state.user);
  const location = useLocation();

  // 切换侧边栏展开/折叠状态
  const toggle = () => {
    setCollapsed(!collapsed);
  };

  // 处理退出登录
  const handleLogout = async () => {
    try {
      await dispatch(logoutUser()).unwrap();
      message.success('退出登录成功');
      // 重定向到登录页
      window.location.href = '/login';
    } catch (error) {
      message.error('退出登录失败，请稍后再试');
    }
  };

  // 用户菜单配置对象
  const userMenu = {
    items: [
      {
        key: '1',
        icon: <UserOutlined />,
        label: <Link to="/profile">个人信息</Link>,
      },
      {
        key: '2',
        icon: <SettingOutlined />,
        label: <Link to="/settings">系统设置</Link>,
      },
      {
        key: '3',
        icon: <LogoutOutlined />,
        label: '退出登录',
        onClick: handleLogout,
      },
    ],
  };

  // 如果未登录，不显示布局，直接显示内容
  if (!isAuthenticated && location.pathname !== '/login') {
    return <div>{children}</div>;
  }

  return (
    <Layout className="app-layout">
      <Header className="header">
        <div className="header-left">
          <Button 
            type="text" 
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />} 
            onClick={toggle} 
            className="toggle-button"
          />
          <h1 className="app-title">设备二维码管理系统</h1>
        </div>
        {isAuthenticated && (
          <div className="header-right">
            <Dropdown menu={userMenu} placement="bottomRight">
              <Button type="text" className="user-button">
                <Avatar icon={<UserOutlined />} />
                <span className="username">{userInfo?.phone || '用户'}</span>
              </Button>
            </Dropdown>
          </div>
        )}
      </Header>
      <Layout>
        {isAuthenticated && (
          <Sider 
            width={200} 
            theme="dark" 
            className="sidebar"
            collapsed={collapsed} 
            collapsible 
            trigger={null}
          >
            <Sidebar collapsed={collapsed} />
          </Sider>
        )}
        <Layout className="content-wrapper">
          <Content className="content">
            {children}
          </Content>
        </Layout>
      </Layout>
    </Layout>
  );
};

export default AppLayout;